package com.tanhua.server.interceptor;

import com.tanhua.domain.db.User;
import com.tanhua.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


//检查token,在什么时候才有token,在登录后才有token
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor{

    @Autowired
    private UserService userService;

    /**
     *
     * @param request
     * @param response
     * @param handler
     * @return   返回值代表是否放行
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(request.getServletPath());
        //1. 获取token
        String token = request.getHeader("Authorization");
        //2. 判断token是否为空,代表该用户没有登陆
        if(token==null){
            response.setStatus(401);
            return false;
        }
        //3. 根据token去查找用户，如果没有查找到，代表该token是失效了
        User user = userService.findUserByToken(token);
        if(user==null){
            response.setStatus(401);
            return false;
        }
        //4. 如果token查找到user，想办法共享出去给controller、service、mapper去使用。
        UserHolder.set(user);
        return true;
    }
}
